package org.skatiger.jrove.impl.jaxb;

import java.util.HashMap;
import java.util.Map;

import org.skatiger.jrove.JroveException;
import org.skatiger.jrove.component.UIComponent;
import org.skatiger.jrove.impl.DefaultViewContext;
import org.skatiger.jrove.impl._ComponentProvider;

public class JaxbComponentProvider implements _ComponentProvider {
	private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory
			.getLogger(JaxbComponentProvider.class);

	public UIComponent createComponent(DefaultViewContext context,
			String componentClass) {
		try {
			Class<UIComponent> clazz = findComponentClass(componentClass);
			UIComponent c = clazz.newInstance();
			return c;
		} catch (Exception e) {
			throw new JroveException("create componentClass " + componentClass
					+ " instance exception.");
		}
	}

	private static final Map<String, Class<UIComponent>> _COMPONENT_CLASSES = new HashMap<String, Class<UIComponent>>();

	private static final Class<UIComponent> findComponentClass(
			String componentClass) {
		Class<UIComponent> _componentClass = _COMPONENT_CLASSES
				.get(componentClass);
		if (_componentClass == null) {
			try {
				_componentClass = JaxbConfigReader.createClass(
						UIComponent.class, componentClass);
				_COMPONENT_CLASSES.put(componentClass, _componentClass);
				logger.debug("found componentClass "
						+ _componentClass.getName());
			} catch (Exception e) {
				logger.error("get component class exception. ", e);
			}
		}
		return _componentClass;

	}

}
